<template>
  <div class="kitchen-management-fixed-layout">
    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
        <el-form-item label="订单号" prop="orderNumber">
          <el-input
            v-model="queryParams.orderNumber"
            placeholder="请输入订单号"
            clearable
            style="width: 180px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="餐台号" prop="tableNumber">
          <el-input
            v-model="queryParams.tableNumber"
            placeholder="请输入餐台号"
            clearable
            style="width: 180px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="出餐状态" prop="kitchenStatus">
          <el-select
            v-model="queryParams.kitchenStatus"
            placeholder="请选择出餐状态"
            clearable
            style="width: 180px"
          >
            <el-option label="全部出餐" value="全部出餐" />
            <el-option label="部分出餐" value="部分出餐" />
            <el-option label="未出餐" value="未出餐" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="recordList"
          border
          class="records-table"
          :height="tableHeight"
        >
          <el-table-column label="序号" type="index" width="70" align="center" />
          <el-table-column label="餐台号" prop="table_number" min-width="100" align="center">
            <template #default="scope">
              <el-tag type="primary" size="large">{{ scope.row.table_number }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="订单号" prop="order_number" min-width="180" align="center">
            <template #default="scope">
              <span class="order-number">{{ scope.row.order_number }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总菜品数" prop="total_items" min-width="110" align="center">
            <template #default="scope">
              <el-tag type="info">{{ scope.row.total_items }} 项</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="已出餐" prop="served_items" min-width="110" align="center">
            <template #default="scope">
              <el-tag type="success">{{ scope.row.served_items }} 项</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="未出餐" prop="pending_items" min-width="110" align="center">
            <template #default="scope">
              <el-tag type="warning">{{ scope.row.pending_items }} 项</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="出餐状态" prop="kitchen_status_text" min-width="120" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.kitchen_status_text === '全部出餐'" type="success">全部出餐</el-tag>
              <el-tag v-else-if="scope.row.kitchen_status_text === '部分出餐'" type="warning">部分出餐</el-tag>
              <el-tag v-else type="info">未出餐</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="开台时间" prop="open_time" min-width="180" align="center">
            <template #default="scope">
              <div class="time-cell">
                <el-icon><Clock /></el-icon>
                <span>{{ formatDateTime(scope.row.open_time) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="最后出餐时间" prop="last_kitchen_time" min-width="180" align="center">
            <template #default="scope">
              <div class="time-cell served-time" v-if="scope.row.last_kitchen_time">
                <el-icon><Check /></el-icon>
                <span>{{ formatDateTime(scope.row.last_kitchen_time) }}</span>
              </div>
              <span v-else class="no-data">-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="showDetails(scope.row)">
                <el-icon><View /></el-icon>
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        class="pagination"
      />
    </el-card>

    <!-- 菜品明细对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`${currentRecord.table_number} - 菜品明细`"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-table :data="detailList" border max-height="500px">
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="菜品名称" prop="menu_name" min-width="150" align="center" />
        <el-table-column label="数量" prop="quantity" width="80" align="center">
          <template #default="scope">
            <el-tag type="warning" size="small">x{{ scope.row.quantity }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="餐品类型" prop="category_type" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.category_type === '前厅'" type="success">前厅</el-tag>
            <el-tag v-else-if="scope.row.category_type === '后厨'" type="primary">后厨</el-tag>
            <el-tag v-else-if="scope.row.category_type === '吧台'" type="warning">吧台</el-tag>
            <el-tag v-else type="info">{{ scope.row.category_type || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="出餐状态" prop="kitchen_status" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.kitchen_status == 1 || scope.row.kitchen_status === '1'" type="success">已出餐</el-tag>
            <el-tag v-else type="warning">待出餐</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" prop="create_time" width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="出餐时间" prop="kitchen_time" width="160" align="center">
          <template #default="scope">
            <span v-if="scope.row.kitchen_time" class="served-time">
              {{ formatDateTime(scope.row.kitchen_time) }}
            </span>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Clock, Check, View } from '@element-plus/icons-vue'
import request from '@/utils/request.js'

const loading = ref(false)
const recordList = ref([])
const total = ref(0)
const detailDialogVisible = ref(false)
const detailList = ref([])
const currentRecord = ref({})
const windowHeight = ref(window.innerHeight)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderNumber: undefined,
  tableNumber: undefined,
  kitchenStatus: undefined,
  dateRange: []
})

// 计算表格高度
const tableHeight = computed(() => {
  // 页面总高度 - 顶部导航(84) - 顶部padding(20) - 搜索卡片(约130) - 卡片padding(40) - 分页(50) - 底部padding(20) - 余量(20)
  return windowHeight.value - 84 - 20 - 130 - 40 - 50 - 20 - 20
})

// 监听窗口大小变化
const handleResize = () => {
  windowHeight.value = window.innerHeight
}

// 查询出餐记录列表（按餐台分组）
function getList() {
  loading.value = true

  const params = {
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
    orderNumber: queryParams.orderNumber,
    tableNumber: queryParams.tableNumber,
    kitchenStatus: queryParams.kitchenStatus
  }

  // 处理日期范围
  if (queryParams.dateRange && queryParams.dateRange.length === 2) {
    params.beginTime = queryParams.dateRange[0] + ' 00:00:00'
    params.endTime = queryParams.dateRange[1] + ' 23:59:59'
  }

  request({
    url: '/restaurant/order/kitchen/records',
    method: 'get',
    params: params
  }).then(response => {
    recordList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
  }).catch(() => {
    loading.value = false
    ElMessage.error('查询失败')
  })
}

// 显示菜品明细
function showDetails(record) {
  currentRecord.value = record
  detailDialogVisible.value = true

  request({
    url: `/restaurant/order/kitchen/details/${record.order_id}`,
    method: 'get'
  }).then(response => {
    detailList.value = response.data || []
  }).catch(() => {
    ElMessage.error('获取明细失败')
  })
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  queryParams.orderNumber = undefined
  queryParams.tableNumber = undefined
  queryParams.kitchenStatus = undefined
  queryParams.dateRange = []

  // 默认查询今天的数据
  const today = new Date()
  const todayStr = today.toISOString().split('T')[0]
  queryParams.dateRange = [todayStr, todayStr]

  getList()
}

// 格式化日期时间
function formatDateTime(time) {
  if (!time) return ''
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

onMounted(() => {
  // 默认查询今天的数据
  const today = new Date()
  const todayStr = today.toISOString().split('T')[0]
  queryParams.dateRange = [todayStr, todayStr]
  getList()

  // 添加窗口大小监听
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除窗口大小监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.kitchen-management-fixed-layout {
  position: relative;
  height: calc(100vh - 84px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background: #f5f7fa;
  box-sizing: border-box;

  .search-card {
    flex-shrink: 0;
    margin-bottom: 20px;
    border-radius: 8px;

    :deep(.el-card__body) {
      padding: 16px 20px;
    }

    .el-form {
      margin-bottom: 0;
    }
  }

  .table-card {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    border-radius: 8px;

    :deep(.el-card__body) {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      padding: 20px;
    }

    .table-wrapper {
      flex: 1;
      overflow: hidden;
    }

    .pagination {
      flex-shrink: 0;
      padding: 12px 0 0 0;
      margin-top: 12px;
    }
  }

  .records-table {
    .order-number {
      font-weight: 600;
      color: #409eff;
    }

    .time-cell {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;
      font-size: 13px;
      color: #606266;

      &.served-time {
        color: #67c23a;
        font-weight: 500;
      }
    }

    .no-data {
      color: #c0c4cc;
      font-size: 13px;
    }
  }
}

// 明细对话框样式
:deep(.el-dialog) {
  .served-time {
    color: #67c23a;
    font-weight: 500;
  }

  .no-data {
    color: #c0c4cc;
  }
}

// iPad 适配
@media screen and (min-width: 768px) and (max-width: 1024px) {
  .kitchen-management-fixed-layout {
    padding: 16px;

    .search-card {
      :deep(.el-card__body) {
        padding: 12px 16px;
      }
    }

    .table-card {
      :deep(.el-card__body) {
        padding: 16px;
      }
    }

    .records-table {
      font-size: 13px;

      :deep(.el-table__cell) {
        padding: 8px 0;
      }
    }
  }

  :deep(.el-dialog) {
    width: 95vw !important;
  }
}
</style>

